package logic

import (
	"api/model/mysql"
	"context"
	"house_srv/house"
	"house_srv/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListHouseLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewListHouseLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListHouseLogic {
	return &ListHouseLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ListHouseLogic) ListHouse(in *house.ListHouseRequest) (*house.ListHouseResponse, error) {
	// todo: add your logic here and delete this line
	page := in.Page
	if page <= 0 {
		page = 1
	}

	pageSize := in.Size
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}

	offset := (page - 1) * pageSize
	var count int64

	var h []mysql.House
	mysql.DB.Find(&h)
	query := mysql.DB.Debug().Model(&mysql.House{})

	if in.StartPrice > 0 {
		query.Where("house_price>=?", in.StartPrice)
	}
	if in.EndPrice > 0 {
		query.Where("house_price<=?", in.EndPrice)
	}

	if in.HouseStatus != 1 {
		query.Count(&count).Offset(int(offset)).Limit(int(pageSize)).Where("house_status=?", in.HouseStatus).Find(&h)
	} else {
		query.Count(&count).Offset(int(offset)).Limit(int(pageSize)).Find(&h)
	}

	var lists []*house.ListHouse

	for _, m := range h {
		listHouse := house.ListHouse{
			HouseCity:    m.HouseCity,
			HouseAddress: m.HouseAddress,
			HouseBuild:   m.HouseBuild,
			HouseFloor:   m.HouseFloor,
			HouseArea:    int64(m.HouseArea),
			HousePrice:   float32(m.HousePrice),
			HouseAuthor:  m.HouseAuthor,
			HouseStatus:  int64(m.HouseStatus),
		}
		lists = append(lists, &listHouse)
	}

	return &house.ListHouseResponse{
		List:  lists,
		Count: count,
	}, nil
}
